package com.bb.blog.code.redis;


import com.weicoder.common.C;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

// 简陋版
// 需要设置过期时间， 自动续时间， 另一个线程竞争锁的时候通过自旋来获取锁
public class RedisLock {
    private String name;


    public RedisLock(String name) {
        this.name = name;

    }

    boolean lock() {
        return new Jedis("127.0.0.1", 6379).setnx(name + "-lock", "1") > 0;
    }

    void unlock() {
        new Jedis("127.0.0.1", 6379).del(name + "-lock");
    }

    public static void main(String[] args) {
//        RedisLock  redisLock = new RedisLock("bb");
        Redisson redisson = (Redisson) Redisson.create();
        RLock redisLock = redisson.getLock("xixix");

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        AtomicInteger atomicInteger = new AtomicInteger(0);
        for (int i = 0; i < 1; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    redisLock.lock();

                    System.out.println(Thread.currentThread().getName() + "获取到了锁" + atomicInteger.incrementAndGet() + System.currentTimeMillis());
                    try {
                        Thread.sleep(20000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "释放了锁" + System.currentTimeMillis());
                    redisLock.unlock();

                }
            });
        }
        executorService.shutdown();


    }




}
